package com.hmall.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 身份校验过滤器
 *
 * @Author mr.wu
 * @Date 2025-6-20 11:49
 */
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    private final JwtTool jwtTool;

    /**
     * 过滤逻辑：校验用户请求中是否携带合法令牌
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求实例和响应实例
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //2.获取请求路径
        String path = request.getURI().getPath();

        //3.判断请求路径是否可放行（请求路径是否在配置文件放行路径的白名单里）
//        List<String> excludePaths = authProperties.getExcludePaths();
//        for (String excludePath : excludePaths) {
//            if(antPathMatcher.match(excludePath, path)) {
//                return chain.filter(exchange);
//            }
//        }

        long count = authProperties.getExcludePaths()
                .stream()
                .filter(excludePath -> antPathMatcher.match(excludePath, path))
                .count();
        if (count > 0) {
            return chain.filter(exchange);
        }

        //4.获取请求头的令牌
        String token = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);

        //5.如果令牌为空，响应401，直接结束
        if (StrUtil.isBlank(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //6.解析令牌
        try {
            Long userId = jwtTool.parseToken(token);
            if (userId == null) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

            // 7.解析令牌成功，设置用户信息到请求头
            request.mutate().header("user-info",userId.toString());
            // 8. 放行请求
            return chain.filter(exchange);
        } catch (Exception e) {
            e.printStackTrace();
            // 9. 响应401，直接结束
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
    }

    //指定执行优先级，值约小优先级越高
    @Override
    public int getOrder() {
        return 0;
    }

}